﻿using System.Net;
using System.Net.Mail;
using System.Text;

/*
 * 通过测试发现如果使用QQ，163等邮箱发送成功了，但对方是否收到还是不能100%达到
 * 
 * 所以我的想法，三次重试的机会，每次采用不同的帐号和不同的邮箱服务器，通过随机号来判断使用哪个邮箱
 * 
 * 也就是你可以在配置文件里配置多个邮箱地址
 */

namespace Ycg.Mail
{
    public class MailManager
    {
        public static void SendMail(MailMessage mailMessage)
        {

        }

        public static void SendMail(MailMessage mailMessage, bool isRetry)
        {
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="from">发送人地址</param>
        /// <param name="displayName">发送人姓名</param>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">标题</param>
        /// <param name="body">正文</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="serverAddress">服务器地址</param>
        /// <param name="attachmemtPath">附件地址</param>
        /// <param name="timeout">发送邮件超时时间(默认10秒)</param>
        public static void SendMail(string from, string displayName, string to, string subject, string body,
                                    string userName, string password, string serverAddress, string attachmemtPath, int timeout = 10000)
        {
            MailMessage mailMessage = new MailMessage
            {
                Body = body,
                Subject = subject,
                IsBodyHtml = true,
                Priority = MailPriority.High,
                BodyEncoding = Encoding.Default,
                From = new MailAddress(from, displayName)
            };

            mailMessage.To.Add(new MailAddress(to));
            mailMessage.Attachments.Add(new Attachment(attachmemtPath));

            SmtpClient smtpClient = new SmtpClient(serverAddress, 25)
            {
                Timeout = timeout,
                UseDefaultCredentials = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential(userName, password),
            };

            smtpClient.Send(mailMessage);
        }
    }
}
